package com.tarena.sentinel.demo02.datasource;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;

import java.net.URL;
import java.util.List;

public class MyRulesDataSource implements InitFunc {

    //如果sentinel加载了自定义数据源 init方法就是读取规则的逻辑方法
    @Override
    public void init() throws Exception {

        // 获取flowRules.json文件的URL
        URL resource =
                MyRulesDataSource.class.getClassLoader().getResource("flowRules.json");
        String filePath = resource.getPath();
        System.out.println("当前文件路径:"+filePath);

        // 读取交给sentinel转化成flowRules对象
        FileRefreshableDataSource dataSource = new FileRefreshableDataSource(filePath, new Converter() {
            @Override
            public Object convert(Object o) {
                // 返回的字符串就是文件的内容
                String json = (String)o;
                System.out.println("读取文件的内容:"+json);
                // 将JSON字符串解析为FlowRule对象列表
                List<FlowRule> flowRules = JSON.parseArray(json, FlowRule.class);
                return flowRules;
            }
        });
        // 将dataSource的属性注册到FlowRuleManager
        FlowRuleManager.register2Property(dataSource.getProperty());

        System.out.println("自定义数据源加载完毕!");
    }
}


